package com.zhentao.datacollection.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.datacollection.domain.dto.StorageStatisticsDTO;
import com.zhentao.datacollection.service.StorageStatisticsService;
import com.zhentao.subscription.common.R;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 入库统计控制器
 */
@RestController
@RequestMapping("/api/datacollection/storage-statistics")
@CrossOrigin(origins = "*")
public class StorageStatisticsController {

    @Autowired
    private StorageStatisticsService storageStatisticsService;

    /**
     * 分页查询入库统计列表
     */
    @GetMapping
    public R<IPage<StorageStatisticsDTO>> getStorageStatisticsPage(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "20") int pageSize,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) String dataType,
            @RequestParam(required = false) String storageStatus) {
        
        try {
            IPage<StorageStatisticsDTO> page = storageStatisticsService.getStorageStatisticsPage(
                pageNo, pageSize, startDate, endDate, dataType, storageStatus);
            return R.ok(page);
        } catch (Exception e) {
            return R.error("查询入库统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取入库统计概览
     */
    @GetMapping("/overview")
    public R<Map<String, Object>> getStatisticsOverview(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        try {
            Map<String, Object> overview = storageStatisticsService.getStatisticsOverview(startDate, endDate);
            return R.ok(overview);
        } catch (Exception e) {
            return R.error("获取统计概览失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有数据类型
     */
    @GetMapping("/data-types")
    public R<List<String>> getAllDataTypes() {
        try {
            List<String> dataTypes = storageStatisticsService.getAllDataTypes();
            return R.ok(dataTypes);
        } catch (Exception e) {
            return R.error("获取数据类型失败: " + e.getMessage());
        }
    }

    /**
     * 导出入库统计数据
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportStorageStatistics(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) String dataType,
            @RequestParam(required = false) String storageStatus,
            @RequestParam(defaultValue = "10000") int maxRecords) {
        
        try {
            List<StorageStatisticsDTO> data = storageStatisticsService.exportStorageStatistics(
                startDate, endDate, dataType, storageStatus, maxRecords);
            
            byte[] excelData = generateExcel(data);
            
            String filename = "storage_statistics_" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + ".xlsx";
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(excelData);
                    
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新增长率
     */
    @PostMapping("/update-growth-rates")
    public R<Void> updateGrowthRates(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        try {
            storageStatisticsService.updateGrowthRates(startDate, endDate);
            return R.ok();
        } catch (Exception e) {
            return R.error("更新增长率失败: " + e.getMessage());
        }
    }

    /**
     * 生成测试数据
     */
    @PostMapping("/generate-test-data")
    public R<Void> generateTestData(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        try {
            storageStatisticsService.generateTestData(startDate, endDate);
            return R.ok();
        } catch (Exception e) {
            return R.error("生成测试数据失败: " + e.getMessage());
        }
    }

    /**
     * 生成Excel文件
     */
    private byte[] generateExcel(List<StorageStatisticsDTO> data) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("入库统计");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {
            "结关日期", "数据类型", "入库状态", "失败原因", "人民币金额值", 
            "美元金额值", "金额同比", "金额环比", "记录条数", "入库时间"
        };
        
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        for (int i = 0; i < data.size(); i++) {
            Row row = sheet.createRow(i + 1);
            StorageStatisticsDTO dto = data.get(i);
            
            row.createCell(0).setCellValue(dto.getClearanceDate() != null ? dto.getClearanceDate().toString() : "");
            row.createCell(1).setCellValue(dto.getDataType() != null ? dto.getDataType() : "");
            row.createCell(2).setCellValue(dto.getStorageStatusText() != null ? dto.getStorageStatusText() : "");
            row.createCell(3).setCellValue(dto.getFailureReason() != null ? dto.getFailureReason() : "");
            row.createCell(4).setCellValue(dto.getRmbAmount() != null ? dto.getRmbAmount().doubleValue() : 0);
            row.createCell(5).setCellValue(dto.getUsdAmount() != null ? dto.getUsdAmount().doubleValue() : 0);
            row.createCell(6).setCellValue(dto.getYearOnYearGrowthText() != null ? dto.getYearOnYearGrowthText() : "");
            row.createCell(7).setCellValue(dto.getMonthOnMonthGrowthText() != null ? dto.getMonthOnMonthGrowthText() : "");
            row.createCell(8).setCellValue(dto.getRecordCount() != null ? dto.getRecordCount() : 0);
            row.createCell(9).setCellValue(dto.getStorageTime() != null ? dto.getStorageTime().toString() : "");
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        workbook.close();

        return outputStream.toByteArray();
    }
}
